package com.herr.springboot.http.rest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author herr05
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        // 添加内容转换器,使用默认的内容转换器
        RestTemplate restTemplate = new RestTemplate(getFactory());
        // 设置编码格式为UTF-8
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        HttpMessageConverter<?> converterTarget = null;
        for (HttpMessageConverter<?> item : converterList) {
            if (item.getClass() == StringHttpMessageConverter.class) {
                converterTarget = item;
                break;
            }
        }
        if (converterTarget != null) {
            converterList.remove(converterTarget);
        }
        HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        converterList.add(1, converter);

        return restTemplate;
    }

    public static SimpleClientHttpRequestFactory getFactory() {

        //如果需要排除一些域名的代理，可以使用http.nonProxyHosts参数
        /*方法一、在启动项目中配置VM Options，添加如下字符串。尽量不要在Custom VM Options配置。
        -Dhttp.proxyHost=proxy.xxx.com -Dhttp.proxyPort=8080 -Dhttps.proxyHost=proxy.xxx.com -Dhttps.proxyPort=8080*/

        /* 方法二、可以代码配置System的代理
        String proxyHost = "proxy.xxx.com";
        String proxyPort = "8080";
        // 对http开启代理
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", proxyPort);
        // 对https也开启代理
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", proxyPort);
         */

        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //单位为ms
        factory.setReadTimeout(10 * 1000);
        //单位为ms
        factory.setConnectTimeout(10 * 1000);

        /* 方法三、配置factory的InetSocketAddress，代理的url网址或ip, port端口
        InetSocketAddress address = new InetSocketAddress("proxy.xxx.com", 8080);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
        factory.setProxy(proxy);*/
        return factory;
    }
}
